import axios from "axios";
import { ElMessage } from 'element-plus'
export const host = import.meta.env.VITE_BASE_API

const req = axios.create({
  baseURL: import.meta.env.VITE_BASE_API as string,
  timeout: 10000,
})

// 请求拦截器
req.interceptors.request.use((config:any) => {
  const token = window.localStorage.getItem('token')
  if(token){
    config.headers['authorization'] = token
  }
  return config;
}, (error:any) => {
  if(error.response.status === 500){
    ElMessage.error(error.response.data.msg || "服务器异常");
    return Promise.reject(error.response.data)
  }
  return Promise.reject(error);
});

// 响应拦截器
req.interceptors.response.use((response:any) => {
  if(response.status === 200){
    return Promise.resolve(response.data)
  }
  return response;
}, (error:any) => {
  if(error.response.status === 500){
    ElMessage.error(error.response.data.msg || "服务器异常");
    return Promise.resolve(error.response.data)
  }
  return Promise.resolve("Http未知错误");
})

export const Request = (url:string,method:'GET'|'POST'|'DELETE'|'PUT',data?:any,other?:any)=>{
  let obj = {
    url:url,
    method:method,
    ...other
  }
  if(method.toLowerCase() === 'get'){
    obj.params = data
  }else if(method.toLowerCase() === 'post'){
    obj.data = data
  }else if(method.toLowerCase() === 'put'){
    obj.data = data
  }
  return req(obj)
}
